import { ref, watch } from 'vue'
import { useFlowStore } from '@/stores/flow'
import { formDefApi } from '@/api/modules/flow/formDef'
import { ElMessage } from 'element-plus'
import { confirm } from '@/utils'
import { FLOW_TASK_KEY_VIEW } from '@/utils/constant'
import { getPermissionConfig } from '../comps/config'

export const useDesign = () => {
  const fs = useFlowStore()
  const saving = ref(false)
  const cleared = ref(false)

  const update = () => {
    if (cleared.value) {
      confirm('表单已清空,确定要保存吗？', updateStructure)
    } else {
      updateStructure()
    }
  }

  const updateStructure = () => {
    if (fs.checkFormJson()) {
      saving.value = true
      formDefApi.updateStructure(fs.designData.structureId, fs.getFormJson()).then(resp => {
        saving.value = false
        if (resp.success) {
          ElMessage.success('表单已保存')
          cleared.value = false
        } else {
          ElMessage.error(resp.message)
        }
      })
    }
  }

  const clear = () => {
    confirm('确定要清空表单吗?', () => {
      fs.comps = []
      cleared.value = true
    })
  }

  watch(
    () => fs.comps.length,
    () => {
      if (fs.comps.length > 0) {
        //场景：点击了清空表单，cleared被置为true, 这时没有点保存，又重新添加了组件，cleared需要被置为false
        cleared.value = false
      }
    }
  )

  watch(
    () => fs.designData.structureId,
    () => {
      if (fs.comps && fs.comps.length > 0) {
        //场景：加载了其他版本，或初始进入
        fs.activeComp(0)
      }
    }
  )

  //获取初始权限
  const getInitPermission = (config: any) => {
    const permission = {} as any
    fs.tasks.forEach((t: any) => {
      permission[t.id] = {
        visible: getPermissionConfig(config).default.visible,
        modify: getPermissionConfig(config).default.modify,
        remove: getPermissionConfig(config).default.remove
      }
    })
    //增加固定查看时的权限初值
    permission[FLOW_TASK_KEY_VIEW] = {
      visible: getPermissionConfig(config).default.visible
    }
    return permission
  }

  return { saving, update, clear, getInitPermission }
}
